package com.university.service.impl;

import com.university.config.MinioConfig;
import com.university.service.MinioService;
import com.university.utility.MinioUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @description: 存储实现类
 **/
@Service
public class MinioServiceImpl implements MinioService {

    @Resource
    private MinioUtils minioUtils;
    @Resource
    private MinioConfig minioConfig;

    @Override
    public boolean bucketExists(String bucketName) {
        return minioUtils.bucketExists(bucketName);
    }

    @Override
    public void makeBucket(String bucketName) {
        minioUtils.makeBucket(bucketName);
    }

    @Override
    public boolean putObject(String bucketName, String objectName, InputStream stream, String contentType) {
        bucketName = getBucketName(bucketName);
        return minioUtils.putObject(bucketName, objectName, stream, contentType);
    }

    @Override
    public boolean removeObject(String bucketName, String objectName) {
        bucketName = getBucketName(bucketName);
        return minioUtils.removeObject(bucketName, objectName);
    }

    @Override
    public void downloadFile(String bucketName, String fileName, HttpServletResponse response) {
        bucketName = getBucketName(bucketName);
        minioUtils.downloadFile(bucketName, fileName, response);
    }

    /**
     * 获取bucketName
     *
     * @param bucketName bucketName
     * @return bucketName
     */
    private String getBucketName(String bucketName) {
        bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
        if (!this.bucketExists(bucketName)) {
            this.makeBucket(bucketName);
        }
        return bucketName;
    }

    /**
     * 获取预览地址
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return 获取预览地址
     */
    @Override
    public String presignedGetObject(String bucketName, String objectName) {
        bucketName = getBucketName(bucketName);
        return minioUtils.presignedGetObject(bucketName, objectName, 7 * 24 * 3600);
    }
}
